'use strict';

var userModel = require('./user.model');
var jwt = require('jwt-simple');
var moment = require('moment');
/*
 * 用户登录
 * */
exports.login = function(req, res) {
    userModel.findOne({email: req.body.email},function(err,user){
        if(!user){
            res.send({code:400,msg:'该用户不存在'});
        }else{
            user.comparePassword(req.body.password,function(err,isMatch){
                if(!isMatch){
                    res.send({code:404,msg:'密码错误'});
                }else{
                    var temp={
                        username:user.username,
                        avator:user.avator,
                        token:createJWT(user)
                    }
                    res.send({code:200,data:temp});
                }
            })
        }
    })
}
/*
 * 用户注册
 * */
exports.register=function(req,res){
    userModel.findOne({email:req.body.email},function(err,user){
        if(user){
            res.send({code:400,msg:'该用户已存在'});
        }else{
            var user=new userModel(req.body);
            user.save(function(err,user){
                if(err){
                    console.log(err);
                }else{
                    var temp={
                        username:user.username,
                        avator:user.avator,
                        token:createJWT(user)
                    }
                    res.send({code:200,data:temp});
                }
            })
        }
    })
}
/*
 * 修改用户信息
 * */
exports.update=function(res,req){
    var user =new userModel(req.body);
    userModel.findOne({email:req.body},{$set:user},function(err){
        if(err){
            console.log(err);
        }else{
            res.send({code:200,msg:'修改成功'})
        }
    })
}

function createJWT(user){
    var payload = {
        sub: user._id,
        iat: moment().unix(),
        exp: moment().add(14, 'days').unix()
    };
    return jwt.encode(payload, 'wjhuang');
}
